import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tx_live_plugin/tx_live_plugin.dart';
import 'package:tx_live_plugin_example/bean/user_model.dart';
import 'package:tx_live_plugin_example/chat_page.dart';
import 'package:tx_live_plugin_example/http/http_client.dart';
import 'package:tx_live_plugin_example/http/url_path.dart';
import 'package:tx_live_plugin_example/play_page.dart';
import 'package:tx_live_plugin_example/push_page.dart';
import 'package:tx_live_plugin_example/util/crypto_utils.dart';
import 'package:tx_live_plugin_example/util/logic_presenter.dart';
import 'package:tx_live_plugin_example/util/toast_utils.dart';
import 'package:tx_live_plugin_example/widget/life_state.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    // 获取到的 licence url
    String licenceURL = "http://license.vod2.myqcloud.com/license/v1/6d2658f3c750c3e6bcb8963c14517018/TXLiveSDK.licence";
    // 获取到的 licence key
    String licenceKey = "62ccf75c2f0451a6ef7e8c8846d15b07";
    TxLivePlugin.initApplicationForPro(licenceURL, licenceKey);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [lifeObserver],
      home: const FirstPage(),
    );
  }
}


class FirstPage extends StatefulWidget{
  const FirstPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage>{

  String _platformVersion = 'Unknown';
  dynamic _videoInfo = r'{"fileName":"20220311160941000000004(直播录像).mp4","createTime":"2022-03-11 16:09:41","evidId":"ab7121aff53811ec9e73005056b9398d"}';
  dynamic _chatInfo;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Wrap(
            spacing: 10,
            runSpacing: 10,
            children: [
              _btn('version:$_platformVersion',onTap: initPlatformState),
              _btn('切换用户类型:${LoginModel.isNotary()? "公证员" : "专业版"}',onTap: (){
                LoginModel.switchUserType();
                setState(() {});
              }),
              _btn('是否登录: ${LogicPresenter.user?.token != null}',onTap: ()async{
                await LoginModel.getToken();
                setState(() {});
              }),
              _btn("直播推流",onTap: _startPush),
              _btn("推流视频播放",onTap: _startPlay),
              _btn("视频会议",onTap: _startChat),
              if(_videoInfo != null)Text("推流：$_videoInfo"),
              if(_chatInfo != null)Text("视频会议：$_chatInfo"),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _init();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion =
          await TxLivePlugin.platformVersion ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Widget _btn(String name, {VoidCallback? onTap}) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(6),
      child: InkWell(
        onTap: onTap,
        child: Container(
          height: 34,
          decoration: BoxDecoration(
            border: Border.all(color: const Color(0xffD4D4D4), width: 1),
            borderRadius: BorderRadius.circular(6),
          ),
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          //left、right
          child: Text(name),
        ),
      ),
    );
  }

  _toPage(Widget page){
    return Navigator.push(context, MaterialPageRoute(builder: (cont)=>page));
  }

  _startPush()async{
    if(ToastUtils.emptyToast(LogicPresenter.user?.token, "token为空，请先登录")){
      return;
    }
    var result = await _toPage(const PushPage());
    //{"fileName":"20220310110505000000001(直播录像).mp4","createTime":"2022-03-10 11:05:05","evidId":"fc231f64a01e11ecbafb005056b9398d"}
    //{"resultData":,"resultCode":"E00000","resultDesc":"成功结束直播录像取证"}
    print("--------------main push finish $result");
    if(result != null) {
      _videoInfo = result;
      if(_videoInfo is Map){
        final prefs = await SharedPreferences.getInstance();
        prefs.setString("pushVideoInfo", jsonEncode(_videoInfo));
      }
      if(mounted)setState(() {});
    }
  }

  void _init()async{
    final prefs = await SharedPreferences.getInstance();
    var info = prefs.getString("pushVideoInfo");
    if(info is String){
      _videoInfo = jsonDecode(info);
    }
    if(mounted )setState(() {});
  }

  void _startPlay() async{
    var tmpUrls = [
      'http://1254421231.vod2.myqcloud.com/e9cda1fbvodcq1254421231/4937c707387702302521631952/f0.mp4',
      // 'http://1254421231.vod2.myqcloud.com/e9cda1fbvodcq1254421231/4937c707387702302521631952/f0.mp4',
      // 'http://1254421231.vod2.myqcloud.com/e9cda1fbvodcq1254421231/4937c707387702302521631952/f0.mp4',
      // 'http://1254421231.vod2.myqcloud.com/e9cda1fbvodcq1254421231/4937c707387702302521631952/f0.mp4',
      // 'http://1254421231.vod2.myqcloud.com/e9cda1fbvodcq1254421231/4937c707387702302521631952/f0.mp4',
    ];
    //进入播放视频页面
    _toPage(PlayPage(urls:tmpUrls));
    return;

    if(_videoInfo is String){
      _videoInfo = jsonDecode(_videoInfo);
    }
    if(_videoInfo is! Map){
      final prefs = await SharedPreferences.getInstance();
      var info = prefs.getString("pushVideoInfo");
      if(info is String){
        _videoInfo = jsonDecode(info);
      }
    }
    if(_videoInfo is! Map){
      Fluttertoast.showToast(msg: "请先录制直播推流视频");
      return;
    }
    var res = await _getEvidenceDetail(_videoInfo['evidId']);
    if(res is! Map){
      Fluttertoast.showToast(msg: "无数据");
      return;
    }
    var li = res['liveJsonArray'];
    List<String> urls = [];
    li?.forEach((element) {
      //视频是否已删除(0-否，1-是)
      if(element['qcloudIsDeleted'] != "1"){
        urls.add(element['videoUrl']);
      }
    });
    if(urls.isEmpty) {
      Fluttertoast.showToast(msg: "无可播放视频地址");
      SharedPreferences.getInstance().then((value){
        value.remove("evidenceInfo");
      });
      return;
    }
    //进入播放视频页面
    _toPage(PlayPage(urls:urls));
  }

  _getEvidenceDetail(String evidId)async{
    final prefs = await SharedPreferences.getInstance();
    var local = prefs.getString("evidenceInfo");
    if(local != null){
      var l = jsonDecode(local);
      if(l['evidId'] == evidId) {
        //本地已缓存 直接用
        return l;
      }
    }
    return await HttpClient.post(UrlPath.EVID_DETAIL, params: {
      "evidId": evidId,
    }, onValue: (res) async{
      prefs.setString("evidenceInfo", jsonEncode(res));
      return res;
    });
  }


  _startChat(){
    if(ToastUtils.toast("请切换公证员版用户登录",error: !LoginModel.isNotary())
        ||ToastUtils.emptyToast(LogicPresenter.user?.token, "token为空，请先登录")){
      return;
    }
    //订单数据
    var order = r'{"id":23997,"orderNum":"210122170519001","paperName":"具结保证书","productName":"股权继承权利具结保证书公证","createTime":"2021/01/22 17:05:19","certificateTime":"2021/01/22 18:07:17","notaryItemName":"保全证据","rejectReason":null,"completeNotarialNum":"（2021）厦鹭证内字第263号","path":"online-notary/stock/2021/0122/7d87d9f0-2ee8-44da-a5a3-bebc43d2c8cc.pdf","orderStatus":3,"orderStatusName":"归档","orderPersonDTOList":[{"personId":"802208301767983104","userId":"702083737533284352","userType":"2","emailAddr":null,"subjectId":null,"subjectAuth":"廖亚程","subjectUniqueCode":null,"subjectIdCard":"350524199205027127","subjectContactName":null,"subjectLegalPersonMobile":null,"subjectContactAddress":"案例是快递放假啊","subjectContactMobile":"13400615954","subjectBusinessLicensePath":null,"idCardPicFront":"/online-notary/person/5f9604be342c449d8aa73de168e1d8fa.jpg","idCardPicBack":"/online-notary/person/0c4ed1417cfd481ea2995b35572de2ee.jpg","subjectType":3,"subjectTypeName":"个人","subjectCaSeriNum":"7941D0404D660C5B2EFC2184BB6F4675","subjectCaCertNotBefore":1587439940000,"subjectCaCertNotAfter":1682047940000,"subjectLegalPersonCaSeriNum":null,"subjectLegalPersonCaCertNotBefore":null,"subjectLegalPersonCaCertNotAfter":null,"signStatus":4,"userSignPic":"/online-notary/signpic/sx_9b8a132846604e28819587f91728469c.png","legalUserSignPic":null,"idType":"111","idTypeName":"居民身份证","gzyRegisterDate":1587431407000,"gzyAccount":"wxgzhqy20200421091002530461","realNameDate":1587439940000,"realNamePicPath":"/liveDetectImage/20190829/9f17d1b2-1ee1-4edb-ab26-35a70fb2ff2e.jpg","legalPersonUserId":null,"legalPersonIdType":null,"legalPersonIdTypeName":"","legalPersonIdCardPicFront":null,"legalPersonIdCardPicBack":null,"country":"","cardType":null,"cardTypeName":null,"notaryNames":null,"notaryitems":null,"cardExpireDate":null,"authExpireDate":null}],"orderTrusteeInfoDTOList":[],"hostNotaryId":"65b1a7dc387d44d8b2ab0dfab4662ade"}';
    var orderMap = jsonDecode(order);
    //接谈数据
    var interview = r'{"id":710,"subjectNames":"廖亚程","appointmentStartTime":"2022/03/23 18:08:00","appointmentEndTime":null,"interviewStatus":0,"notaryId":"65b1a7dc387d44d8b2ab0dfab4662ade","initiate":true}';
    var interviewMap = jsonDecode(interview);
    _toPage(ChatPage(
      interviewId: "${interviewMap['id']}",
      orderNo: orderMap['orderNum'],
      productNo: orderMap['productNo'],
      meetType: MEETING_TYPE_INTERVIEW,
    ));
  }
}

///登录处理
class LoginModel {
  LoginModel._();

  static UserLogin? userLogin = NormalUserLogin();

  ///切换用户类型
  static switchUserType(){
    bool curNotary = !isNotary();
    if(curNotary) {
      userLogin = NotaryUserLogin();
    } else {
      userLogin = NormalUserLogin();
    }
    //清空用户
    LogicPresenter.saveUserInfo(null);
  }

  ///当前用户是否是  公证员版
  static bool isNotary(){
    return userLogin is NotaryUserLogin;
  }

  ///获取登录信息
  static Future<bool?> getToken() async {
    return userLogin?.getToken();
  }
}

///获取用户登录信息
abstract class UserLogin{

   Map<String,dynamic> getUserInfo();

   Future<bool?> getToken();
}

///公证云专业版app的登录信息
class NormalUserLogin with UserLogin{

  @override
  Map<String, dynamic> getUserInfo() {
    return const {
      "userName": "13400615954",
      "appType": "405",
      "info": [
        {
          //亚程账号
          "userName": "13400615954",
          "password": "aaa111",
          "userType": "2",
        }, //可设置其他账号，取账号根据外层的userName
      ]
    };
  }

  @override
  Future<bool?> getToken() async{
    var loginInfo = getUserInfo();
    var account = loginInfo["userName"];
    List _info = loginInfo['info'];
    Map info = _info.firstWhere((element) => element['userName'] == account);
    var _pwd = info["password"];
    var userType = info["userType"];
    var pwd = await CryptoUtils.md5String(_pwd);
    return await HttpClient.post(UrlPath.LOGIN, params: {
      "userName": account,
      "password": pwd,
      "userType": userType,
      //"inviteCode": invite
    }, onValue: (res) {
      LogicPresenter.saveUserInfo(UserModel.fromJson(res));
      return true;
    });
  }
}

///公证员版app的登录信息
class NotaryUserLogin with UserLogin{
  @override
  Future<bool?> getToken() async{
    var loginInfo = getUserInfo();
    var account = loginInfo["userName"];
    List _info = loginInfo['info'];
    Map info = _info.firstWhere((element) => element['userName'] == account);
    var _pwd = info["password"];
    var pwd = await CryptoUtils.md5String(_pwd);
    return await HttpClient.post(UrlPath.NOTARY_LOGIN, params: {
      "notaryAccount": account,
      "password": _pwd,//pwd,
    }, onValue: (res) {
      LogicPresenter.saveUserInfo(UserModel.fromJson(res));
      return true;
    });
  }

  @override
  Map<String, dynamic> getUserInfo() {
    return const {
      "userName": "liaoyacheng",
      "appType": "405",
      "info": [
        {
          //亚程账号
          "userName": "liaoyacheng",
          "password": "aaa111",
        }, //可设置其他账号，取账号根据外层的userName
      ]
    };
  }

}
